package ops.weixin.common.error;

import java.io.Serializable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import ops.weixin.common.WxType;
import ops.weixin.cp.util.StringUtils;

/**
 * 微信错误码. 请阅读： 公众平台：<a href=
 * "http://mp.weixin.qq.com/wiki/10/6380dc743053a91c544ffd2b7c959166.html">全局返回码说明</a>
 * 企业微信：<a href="https://work.weixin.qq.com/api/doc#10649">全局错误码</a>
 *
 */
public class WxError implements Serializable {
	private static final long serialVersionUID = 7869786563361406291L;

	/**
	 * 微信错误代码.
	 */
	private int errorCode;

	/**
	 * 微信错误信息. （如果可以翻译为中文，就为中文）
	 */
	private String errorMsg;

	/**
	 * 微信接口返回的错误原始信息（英文）.
	 */
	private String errorMsgEn;

	private String json;

	public static WxError fromJson(String json) {
		return fromJson(json, null);
	}

	public static WxError fromJson(String json, WxType type) {
		JSONObject jsonObject = JSONObject.parseObject(json);
		WxError wxError = JSON.toJavaObject(jsonObject, WxError.class);

		if (wxError.getErrorCode() == 0 || type == null) {
			return wxError;
		}

		if (StringUtils.isNotEmpty(wxError.getErrorMsg())) {
			wxError.setErrorMsgEn(wxError.getErrorMsg());
		}

		switch (type) {
		case CP: {
			final String msg = WxCpErrorMsgEnum.findMsgByCode(wxError.getErrorCode());
			if (msg != null) {
				wxError.setErrorMsg(msg);
			}
			break;
		}
		default:
			return wxError;
		}

		return wxError;
	}

	public int getErrorCode() {
		return errorCode;
	}

	public WxError setErrorCode(int errorCode) {
		this.errorCode = errorCode;
		return this;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public WxError setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
		return this;
	}

	public String getErrorMsgEn() {
		return errorMsgEn;
	}

	public WxError setErrorMsgEn(String errorMsgEn) {
		this.errorMsgEn = errorMsgEn;
		return this;
	}

	public String getJson() {
		return json;
	}

	public WxError setJson(String json) {
		this.json = json;
		return this;
	}

	@Override
	public String toString() {
		if (this.json == null) {
			return "错误代码：" + this.errorCode + ", 错误信息：" + this.errorMsg;
		}

		return "错误代码：" + this.errorCode + ", 错误信息：" + this.errorMsg + "，微信原始报文：" + this.json;
	}

}
